var superagent = require('superagent');
var cheerio = require('cheerio');
var async = require('async');
var mysql = require('mysql');



var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'node',
});
connection.connect();

var linkA = [];

for (var i = 1; i < 3; i++) {
    var url = 'http://www.g-emall.com/catalog/list?categoryID=791&pageIndex=' + i + '&pageSize=60';
    superagent.get(url).end(function(err, mes) {
        if (err) {
            console.log("出问题了1:" + err);
        } else {
            var $ = cheerio.load(mes.text);
            $(".goods-main li").each(function() {
                //var _title=$(this).find('a').attr('title');
                //var _img=$(this).find('img').attr('src');
                var _href = $(this).find('a').attr('href');
                linkA.push(_href);
            });
        }
    });
}

var t=0;
setTimeout(function(){
    get();
},8000);

function get() {

    async.mapLimit(linkA, 2, function(url, callback) {
        
        superagent.get(url).end(function(err, mes) {
            if (err) {
                console.log("出问题了2:" + err);
            } else {
                t++;
                var $ = cheerio.load(mes.text);
                var _type=2;
                var _title = $(".pd-info1").attr('title');
                var _txtle = $(".pd-info2").text();
                $(".pd-info5").find('span').remove();
                var _prie = $(".pd-info5").text().replace(/(^\s*)|(\s*$)/g, "");
                var _img = $(".jqzoom img").attr('alt');
                var _cont = $("#tabCon_pdTab_01").html();

                var userinto = 'INSERT INTO gaiwang(type,title,txtle,prie,img,cont) VALUES(?,?,?,?,?,?)';
                var userinto_Params = [_type,_title,_txtle,_prie,_img,_cont];
                connection.query(userinto, userinto_Params, function(err, result) {
                    if (err) {
                        console.log('[ERROR] - ', err.message);
                        return;
                    }else{
                        console.log("成功加入");
                    }
                });


                console.log(t);
                console.log(_prie);
            };
            callback(null);
        });

    });

}
